package com.srwl.mytx.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Helper;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Transfer;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.AliService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 提现页面
 * 管理员可见
 */
public class WithdrawActivity extends BaseActivity {
    public static void startActivity(Context context, Transfer transfer) {
        context.startActivity(new Intent(context, WithdrawActivity.class).putExtra(Constant.EXTRA_INFO_TRANSFER, transfer));
    }

    private static final String TAG = "WithdrawActivity";
    private static final int REQUEST_CODE_REFUND = 0;
    private static final int REQUEST_CODE_ORDER_SEND = 1;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;

    @BindView(R.id.iv_avatar)
    ImageView iv_avatar;
    @BindView(R.id.tv_username)
    TextView tv_username;
    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_account)
    TextView tv_account;
    @BindView(R.id.tv_apply_time)
    TextView tv_applyTime;
    @BindView(R.id.tv_transfer_status)
    TextView tv_transfer_status;
    @BindView(R.id.tv_id)
    TextView tv_Id;
    @BindView(R.id.tv_order_id)
    TextView tv_orderId;
    @BindView((R.id.ll_pay_complete))
    RelativeLayout ll_payComplete;
    @BindView(R.id.tv_pay_time)
    TextView tv_pay_time;
    @BindView(R.id.bottom_bar)
    ConstraintLayout bottomBar;
    @BindView((R.id.btn_commit))
    Button btn_commit;
    @BindView((R.id.btn_error))
    Button bth_error;
    @BindView(R.id.et_trade_no)
    EditText et_tradeNo;
    private Transfer transfer;
    private User targetUser;
    private boolean isSync;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdraw);
        ButterKnife.bind(this);
        transfer = getIntent().getParcelableExtra(Constant.EXTRA_INFO_TRANSFER);
        if (transfer == null) {

            Log.e(TAG, "onCreate: transfer不能为空，，，");
        } else {
            targetUser = transfer.getTargetUser();
            syncData(transfer.getId());
        }
    }

    /**
     * 在页面中展示数据
     */
    private void setViewAndEvent() {

        tv_amount.setText(Utils.moneyFormat(transfer.getAmount()));
        tv_account.setText(transfer.getAliAccount());
        tv_Id.setText(transfer.getId());
        tv_applyTime.setText(DateUtils.dateToString(transfer.getCreateDate(), DateUtils.FORMAT_TIMESTAMP));
        if (targetUser != null) {
            //Glide.with(WithdrawActivity.this).load(targetUser.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar).into(iv_avatar);
            GlideLoadUtils.glideLoad(this, targetUser.getAvatar(), iv_avatar, R.drawable.tx_default_avatar_1);
            tv_username.setText(targetUser.getUsername());
            iv_avatar.setOnClickListener(v -> contact(targetUser));
            tv_username.setOnClickListener(v -> contact(targetUser));
        }
        switch (transfer.getStatus()) {

            case Constant.ORDER_TRANSFER_APPLY_STATUS:
                tv_transfer_status.setText("申请提现");
                ll_payComplete.setVisibility(View.GONE);
                bottomBar.setVisibility(View.VISIBLE);
                et_tradeNo.setVisibility(View.VISIBLE);
                btn_commit.setOnClickListener(v -> showCommitDialog());
                bth_error.setOnClickListener(v -> transferError());
                break;
            case Constant.ORDER_TRANSFER_SUCCESS_STATUS:
                tv_transfer_status.setText("提现成功");
                ll_payComplete.setVisibility(View.VISIBLE);
                tv_orderId.setText(transfer.getOrderId());
                tv_pay_time.setText(DateUtils.dateToString(transfer.getPayDate(), DateUtils.FORMAT_TIMESTAMP));
                bottomBar.setVisibility(View.GONE);
                et_tradeNo.setVisibility(View.GONE);
                break;
            case Constant.ORDER_TRANSFER_ERROR_STATUS:
                tv_transfer_status.setText("异常提现订单,请联系客服");
                ll_payComplete.setVisibility(View.VISIBLE);
                tv_pay_time.setText(DateUtils.dateToString(transfer.getPayDate(), DateUtils.FORMAT_TIMESTAMP));
                bottomBar.setVisibility(View.GONE);
                et_tradeNo.setVisibility(View.GONE);
                break;
        }
    }

    private void contact(User userInfo) {
        WithdrawActivity.this.startActivity(new Intent(WithdrawActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));
    }


    /**
     * 提现订单成功
     */
    private void showCommitDialog() {

        if (TextUtils.isEmpty(et_tradeNo.getText().toString().trim())) {
            showToast(btn_commit, "请输入第三方转账订单号");
            return;
        }
        ConfirmDialog dialog = new ConfirmDialog(this, "提醒", "您确定已经给用户转账成功?", "确定", "取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                progressBar.setVisibility(View.VISIBLE);
                transfer.setOrderId(et_tradeNo.getText().toString().trim());
                RetrofitManager.getInstance().createRequest(AliService.class)
                        .transferSuccess(transfer)
                        .enqueue(new Callback<CommonResult>() {
                            @Override
                            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                                progressBar.setVisibility(View.GONE);
//                                btn_success.setVisibility(View.GONE);
//                                btn_success.setVisibility(View.GONE);
                                CommonResult result = response.body();
                                if (!response.isSuccessful() || result == null) {
                                    Log.i(TAG, "onResponse: " + response.message());
                                    showToast(getString(R.string.system_busy));
                                    setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TRANSFER, transfer));
                                    return;
                                }
                                if (result.isError()) {
                                    Log.i(TAG, "onResponse: " + result.getMsg());
                                    switch (result.getStatus()) {
                                        case Constant.RETURN_HTTP_STATUS_TRANSFER_ORDER_NOT_EXIST:
                                            setViewAndEvent();
                                            setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TRANSFER, transfer));
                                            showToast("您提交的提现订单不存在");
                                            break;
                                        default:
                                            setViewAndEvent();
                                            setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TRANSFER, transfer));
                                            showToast(getString(R.string.system_busy));
                                    }
                                    return;
                                }
                                Object object = result.getData();
                                Log.i(TAG, "onResponse:提现订单处理成功");
                                WithdrawActivity.this.transfer.setStatus(Constant.ORDER_TRANSFER_SUCCESS_STATUS);
                                WithdrawActivity.this.transfer.setPayDate(new Date());
                                setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TRANSFER, WithdrawActivity.this.transfer));
                                setViewAndEvent();
                                showToast("处理成功");
                            }

                            @Override
                            public void onFailure(Call<CommonResult> call, Throwable t) {
                                progressBar.setVisibility(View.GONE);
//                                btn_success.setVisibility(View.VISIBLE);
//                                btn_success.setVisibility(View.VISIBLE);
                                Log.i(TAG, "onFailure: " + t.getMessage());
                                showToast(getString(R.string.system_busy));
                            }
                        });

            }
        });
        dialog.show();

    }

    /**
     * 提现订单失败
     */
    private void transferError() {
        ConfirmDialog dialog = new ConfirmDialog(this, "提醒", "您确定该用户是非法提现?", "确定", "取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {

            @Override
            public void confirm() {
                if (!Helper.getInstance().isNetworkConnected()) {
                    showToast_v1(getString(R.string.network_anomalies));
                    return;
                }
                progressBar.setVisibility(View.VISIBLE);
                RetrofitManager.getInstance().createRequest(AliService.class)
                        .transferError(transfer.getId())
                        .enqueue(new Callback<CommonResult>() {
                            @Override
                            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
//                                btn_success.setVisibility(View.GONE);
//                                btn_success.setVisibility(View.GONE);
                                progressBar.setVisibility(View.GONE);
                                CommonResult result = response.body();
                                if (!response.isSuccessful() || result == null) {
                                    Log.i(TAG, "onResponse: " + response.message());
                                    showToast(getString(R.string.system_busy));
                                    setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TRANSFER, transfer));
                                    return;
                                }
                                if (result.isError()) {
                                    Log.i(TAG, "onResponse: " + result.getMsg());
                                    switch (result.getStatus()) {
                                        case Constant.RETURN_HTTP_STATUS_TRANSFER_ORDER_NOT_EXIST:
                                            setViewAndEvent();
                                            setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TRANSFER, transfer));
                                            showToast("您提交的提现订单不存在");
                                            break;
                                        default:
                                            setViewAndEvent();
                                            setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TRANSFER, transfer));
                                            showToast(getString(R.string.system_busy));
                                    }
                                    return;
                                }
                                Object object = result.getData();
                                JSONObject transferJson = (JSONObject) object;
                                Transfer updateTransfer = JSONObject.toJavaObject(transferJson, Transfer.class);
                                Log.i(TAG, "onResponse:提现订单处理成功");
                                WithdrawActivity.this.transfer.setStatus(Constant.ORDER_TRANSFER_ERROR_STATUS);
                                WithdrawActivity.this.transfer.setPayDate(updateTransfer.getPayDate());
                                setViewAndEvent();
                                setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TRANSFER, transfer));
                                showToast("处理成功");
                            }

                            @Override
                            public void onFailure(Call<CommonResult> call, Throwable t) {
                                progressBar.setVisibility(View.GONE);
//                                btn_success.setVisibility(View.VISIBLE);
//                                btn_success.setVisibility(View.VISIBLE);
                                Log.i(TAG, "onFailure: " + t.getMessage());
                                showToast(getString(R.string.system_busy));
                            }
                        });
            }
        });
        dialog.show();
    }

    private void syncData(String transferId) {
        if (isSync) {
            return;
        }
        isSync = true;
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(AliService.class)
                .getTransferInfo(transferId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        isSync = false;
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        Log.d(TAG, "onResponse: 同步信息完成");
                        JSONObject body = (JSONObject) result.getData();
                        if (body == null) {
                            return;
                        }
                        transfer = body.toJavaObject(Transfer.class);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TRANSFER, transfer));
                        setViewAndEvent();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        isSync = false;
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

    }
}
